module Sessionable
  extend ActiveSupport::Concern

  included do
    attr_writer :current_user

    def current_user
      if sign_in_token_valid?
        if @current_user.blank?
          redis_expire(get_cookie(:sign_in_token),
                                  SIGN_IN_TOKEN_EXPIRE_TIME)
          @current_user =
            User.find(redis_get(get_cookie(:sign_in_token)))
        else
          @current_user
        end
      end
    end

    # def current_user_id
    #   if sign_in_token_valid?
    #     $redis_connection.expire(get_cookie(:sign_in_token),
    #                             SIGN_IN_TOKEN_EXPIRE_TIME)
    #     $redis_connection.get(get_cookie(:sign_in_token))
    #   end
    # end

    # def current_user?(user)
    #   user == current_user
    # end
      
    def signed_in_user
      unless signed_in?
        flash[:danger] = I18n.t "please_sign_in"
        redirect_to '/sign_in'
      end
    end

    def sign_in(user)
      set_cookie(:sign_in_token, new_secure_token)
      redis_set(get_cookie(:sign_in_token),
                            user.id.to_s,
                            ex: SIGN_IN_TOKEN_EXPIRE_TIME)
      current_user = user
    end

    def signed_in?
      sign_in_token_valid?
    end

    def sign_out
      reset_session
      redis_del(get_cookie(:sign_in_token))
      cookies.delete(:sign_in_token)
      session.destroy
      current_user = nil
    end

    # def store_location
    #   session[:return_to] = request.fullpath if request.get?
    # end

    private
      def sign_in_token_valid?
        sign_in_token = get_cookie(:sign_in_token)
        sign_in_token && redis_exists(sign_in_token)
      end

      def get_cookie(key)
        cookies[key]
      end

      def set_cookie(key, value)
        cookies.permanent[key] = value
      end
    
      def new_secure_token
        SecureRandom.urlsafe_base64
      end
  end
end